#!/bin/bash

DB_PATH=/opt/kingbase
DATA_DIR=${DB_PATH}/data
LOG_FILE=${DB_PATH}/logfile

check_is_init() {
	declare -g DATABASE_EXISTS
	if [ -d "${DATA_DIR}" -a `ls -A ${DATA_DIR}|wc -w` -ne 0 ]; then
		DATABASE_EXISTS='true'
	fi
}

db_start(){
	${DB_PATH}/Server/bin/sys_ctl -D ${DATA_DIR} -l ${LOG_FILE} start
}

db_init(){
	#${DB_PATH}/Server/bin/initdb -m pg -D ${DATA_DIR} -U SYSTEM --pwfile=${DB_PATH}/pwfile -E UTF8
	${DB_PATH}/Server/bin/initdb -D ${DATA_DIR} -U SYSTEM --pwfile=${DB_PATH}/pwfile -E UTF8
	sed -i '1ihost kingbase SYSTEM 0.0.0.0/0 password' ${DATA_DIR}/sys_hba.conf
	db_start
	${DB_PATH}/Server/bin/createdb -E UTF8 -O SYSTEM -U SYSTEM kingbase
}

check_is_init
if [ -z "${DATABASE_EXISTS}" ]; then
	db_init
	if [ $? -ne 0 ]; then
		echo "initdb failed"
		exit 1
	fi
else
	db_start
fi

exec tail -f ${LOG_FILE}
